from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from frame_server.serializers import BaseSerializer as BSerializer
from .models import Dept

# 新增/编辑验证基类
class AddEditValidateBase(BSerializer):
    parentId = serializers.IntegerField(required=False, allow_null=True)
    deptName = serializers.CharField(
        max_length=255,
        validators=[UniqueValidator(queryset=Dept.objects.all(), message="部门名称已存在")]
    )
    class Meta:
        model = Dept

    def validate_parentId(self, val):
        if val:
            if not Dept.objects.filter(id=val).exists():
                raise serializers.ValidationError("上级部门不存在")
            return Dept.objects.only('id').get(id=val)
        return None
    
# 新增
class AddValidate(AddEditValidateBase):
    
    class Meta(AddEditValidateBase.Meta):
        exclude = ['id']

# 编辑
class EditValidate(AddEditValidateBase):
    id = serializers.IntegerField()
    
    def validate_id(self, val):
        if not Dept.objects.filter(id=val).exists():
            raise serializers.ValidationError("编辑对象不存在")
        return val
    
    class Meta(AddEditValidateBase.Meta):
        fields = '__all__'
